<?php
namespace service;

use think\Cache;
use app\common\model as M;
/**
 * 秀米编辑器接口
 * @see https://ent.xiumi.us/doc2.html
 * Class XiumiEditorService
 * @package service
 */

class XiumiEditorService
{
    const SYNC_ARTICL_KEY = 'CRTJUSTALLOWONE2024';

    protected $appid;
    protected $apiSecret;
    protected $baseUrl = 'https://xiumi.us';
	
    public function __construct()
    {
        $this->appid = \think\Env::get('XIUMIEDITOR.APP_ID');
        $this->apiSecret = \think\Env::get('XIUMIEDITOR.APP_SECRET');
    }
	
    /**
     * 生成绑定秀米账户的URL
     * @Author   FW
     * @DateTime 2021-04-08
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function generateBindUrl()
    {
        $params = [
            'timestamp'       => time(),
            'nonce'           => uniqid(),
            'partner_user_id' => \think\Env::get('XIUMIEDITOR.PARTNER_UID'),
            'appid'           => $this->appid,
            'bind_name'       => \think\Env::get('XIUMIEDITOR.BIND_NAME'),
        ];
        $params['signature'] = $this->generateSignature($params['timestamp'],$params['nonce'] , $params['partner_user_id']);
        return sprintf("%s/auth/partner/bind?%s" , $this->baseUrl , http_build_query($params));
    }

    /**
     * 生成绑定秀米账户的URL
     * @Author   FW
     * @DateTime 2021-04-08
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function generateEditUrl($article_id = 0)
    {
        $params = [
            'open_id' => \think\Env::get('XIUMIEDITOR.OPENID'),
        ];
        if ( $article_id > 0 ) $params['article_id'] = $article_id;
        return sprintf("%s/auth/partner/edit?%s" , $this->baseUrl , http_build_query($params));
    }

    /**
     * 检查秀米是否有权调用接口
     * @Author   FW
     * @DateTime 2021-04-08
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    public function checkAuth($headerSecret)
    {
        $allowSecret = sprintf('secret %s',$this->apiSecret);
        return $headerSecret == $allowSecret;
    }

    /**
     * 生成签名
     * @Author   FW
     * @DateTime 2021-04-08
     * @Email    123763712@qq.com
     * @return   [type]           [description]
     */
    protected function generateSignature($timestamp , $nonce, $partner_user_id)
    {
        $params = [$this->apiSecret, $timestamp , $nonce, $partner_user_id];
        sort($params, SORT_STRING);
        return md5(md5(implode($params)));
    }
}